package com.liangxy.news.ui.main.profile;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.liangxy.news.R;
import com.liangxy.news.model.News;
import com.liangxy.news.repository.NewsRepository;
import com.liangxy.news.ui.main.home.NewsAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * Fragment to display user's followed news
 */
public class FollowedNewsFragment extends Fragment {
    
    private static final String TAG = "FollowedNewsFragment";
    private static final String ARG_USER_ID = "user_id";
    
    private String userId;
    private RecyclerView rvFollowedNews;
    private ProgressBar progressBar;
    private TextView tvNoData;
    private Toolbar toolbar;
    
    private NewsAdapter newsAdapter;
    private NewsRepository newsRepository;
    
    /**
     * Create a new instance of FollowedNewsFragment
     * @param userId User ID
     * @return FollowedNewsFragment instance
     */
    public static FollowedNewsFragment newInstance(String userId) {
        FollowedNewsFragment fragment = new FollowedNewsFragment();
        Bundle args = new Bundle();
        args.putString(ARG_USER_ID, userId);
        fragment.setArguments(args);
        return fragment;
    }
    
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            userId = getArguments().getString(ARG_USER_ID);
        }
        
        try {
            // 初始化新闻仓库
            newsRepository = NewsRepository.getInstance(requireContext().getApplicationContext());
            Log.d(TAG, "初始化NewsRepository成功");
        } catch (Exception e) {
            Log.e(TAG, "初始化NewsRepository失败: " + e.getMessage(), e);
        }
    }
    
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_followed_news, container, false);
        
        // 初始化组件
        rvFollowedNews = view.findViewById(R.id.rvFollowedNews);
        progressBar = view.findViewById(R.id.progressBar);
        tvNoData = view.findViewById(R.id.tvNoData);
        toolbar = view.findViewById(R.id.toolbar);
        
        // 设置工具栏
        try {
            if (getActivity() instanceof AppCompatActivity) {
                AppCompatActivity activity = (AppCompatActivity) getActivity();
                
                // 备份原ActionBar
                toolbar.setTitle(R.string.followed_news);
                toolbar.setNavigationIcon(R.drawable.ic_back);
                
                // 设置返回按钮点击事件
                toolbar.setNavigationOnClickListener(v -> {
                    if (getActivity() != null && getActivity().getSupportFragmentManager().getBackStackEntryCount() > 0) {
                        getActivity().getSupportFragmentManager().popBackStack();
                    }
                });
            }
        } catch (Exception e) {
            Log.e(TAG, "设置工具栏时出错: " + e.getMessage(), e);
        }
        
        // 设置RecyclerView
        rvFollowedNews.setLayoutManager(new LinearLayoutManager(requireContext()));
        newsAdapter = new NewsAdapter(new ArrayList<>());
        if (newsRepository != null) {
            newsAdapter.setNewsRepository(newsRepository, userId);
        }
        rvFollowedNews.setAdapter(newsAdapter);
        
        return view;
    }
    
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        
        // 加载关注的新闻
        loadFollowedNews();
    }
    
    /**
     * 加载关注的新闻
     */
    private void loadFollowedNews() {
        showLoading();
        
        if (userId == null || userId.isEmpty()) {
            showNoData();
            return;
        }
        
        try {
            // 使用NewsRepository加载关注的新闻
            newsRepository.getFollowedNews(userId).observe(getViewLifecycleOwner(), newsList -> {
                if (newsList != null && !newsList.isEmpty()) {
                    showNewsList(newsList);
                } else {
                    showNoData();
                }
            });
        } catch (Exception e) {
            Log.e(TAG, "加载关注新闻失败: " + e.getMessage(), e);
            showErrorView(e.getMessage());
        }
    }
    
    /**
     * 显示加载中状态
     */
    private void showLoading() {
        progressBar.setVisibility(View.VISIBLE);
        tvNoData.setVisibility(View.GONE);
        rvFollowedNews.setVisibility(View.GONE);
    }
    
    /**
     * 显示无数据状态
     */
    private void showNoData() {
        progressBar.setVisibility(View.GONE);
        tvNoData.setVisibility(View.VISIBLE);
        rvFollowedNews.setVisibility(View.GONE);
    }
    
    /**
     * 显示新闻列表
     * @param newsList 新闻列表
     */
    private void showNewsList(List<News> newsList) {
        progressBar.setVisibility(View.GONE);
        tvNoData.setVisibility(View.GONE);
        rvFollowedNews.setVisibility(View.VISIBLE);
        
        newsAdapter.updateData(newsList);
        Log.d(TAG, "Loaded " + newsList.size() + " followed news");
    }
    
    /**
     * 显示错误信息
     * @param errorMsg 错误信息
     */
    private void showErrorView(String errorMsg) {
        if (getContext() == null) return;
        
        progressBar.setVisibility(View.GONE);
        tvNoData.setVisibility(View.VISIBLE);
        tvNoData.setText(getString(R.string.error_loading_data) + "\n" + errorMsg);
        rvFollowedNews.setVisibility(View.GONE);
    }
} 